<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-operator" ref="popoverWrapperRef" v-clickOutside="hiddenPopover">
        <a-row :gutter="42" v-if="pageNum == 1">
          <a-col :md="17" :sm="7">
            <span class="table-page-search-submitButtons" :style="{ float: 'left', overflow: 'hidden' }">
              <a-button @click="switchPage">返回</a-button>
              <a-button type="primary" @click="handleAdd">上传APP</a-button>
            </span>
          </a-col>
        </a-row>
        <div>
          <a-popover :getPopupContainer="getPopupContainer" placement="bottomRight" :visible="popoverVisible">
            <template #title>
              <!-- <CloseSquareOutlined @click="popoverVisible = false" /> -->
              <a-form class="div" ref="modalFormRef" :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <!-- <a-form-item label="版本号" class="item" name="versionNumber" :wrapper-col="{ span: 24, offset: 0 }">    -->
                <a-form-item label="版本号" class="item" name="versionNumber">
                  <a-input v-model="form.versionNumber" placeholder="请输入版本号" />
                </a-form-item>
                <a-form-item label="平台" class="item" name="name">
                  <a-select v-model="form.tagNameId" :getPopupContainer="getPopupContainer" @change="getMemoryList">
                    <a-select-option :value="item.id" v-for="(item, index) in platformList" :key="index">{{
                      item.name
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="产物类型" class="item" name="internalStorage">
                  <a-select
                    v-model="form.internalStorage"
                    :getPopupContainer="getPopupContainer"
                    :disabled="!form.tagNameId"
                  >
                    <a-select-option :value="item" v-for="(item, index) in memoryList" :key="index">{{
                      item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="创建时间" class="item" name="creationTime">
                  <a-range-picker v-model="form.creationTime" :getCalendarContainer="getPopupContainer" />
                </a-form-item>
                <!-- <a-form-item required label="平台标识" name="tagSystem" >
                    <a-input v-model="form.tagSystem"/>
                  </a-form-item>
                  <a-form-item required label="产物类型" name="supports" >
                    <a-select mode="multiple" v-model="form.supports">
                      <a-select-option :value="item" v-for="(item,index) in memoryList" :key="index">{{item}}</a-select-option>
                    </a-select>
                  </a-form-item> -->
              </a-form>
            </template>
            <template #content>
              <a-button @click="formtoList">查询</a-button>
              <a-button @click="reformtoList">重置</a-button>
            </template>
          </a-popover>
        </div>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="pageNum==0?columns:columnsApp"
        :data="loadData"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="name" slot-scope="text, record, index">
          <a @click="toApp(record)">{{ record.name }}</a>
        </span>
        <span slot="supports" slot-scope="record">
          {{ getSupportsTest(record) }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEditState(record)">{{ record.state?'上线':'下线' }}</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)">修改</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :mdlStatus="mdlStatus"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk" />
      <app-modal
        ref="appModal"
        :visible="appModalVisible"
        :tagId="appForm.tagId"
        :tagName="appForm.tagName"
        :model="mdl"
        @cancel="appModalCancel"
        @ok="appModalOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getAppList, setApp, setAppState, addApp, delAppState, verifyAppUpload } from '@/api/app'
import { getTagNameList } from '@/api/platform'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import { addVersion, delVersions, updateVersions, isExistVersion } from '@/api/versions'
import { mapActions } from 'vuex'
import { computeMD5 } from '@/utils/upload'
import { Modal } from 'ant-design-vue'
import { CloseSquareOutlined } from '@ant-design/icons-vue'
import clickOutside from '@/core/directives/clickout'
import { sleep } from '@/utils/util'

import AppModal from './components/AppModal.vue'
import {base64ToFile} from '@/utils/file'

const columns = [
  {
    title: '序号',
    dataIndex: 'serialNumber',
    width: '150px'
    // scopedSlots: { customRender: 'serial' }
  },
  {
    title: '平台',
    dataIndex: 'name',
    // dataIndex: 'name'
    scopedSlots: { customRender: 'name' }
  }
  // ,
  // {
  //   title: '操作',
  //   dataIndex: 'action',
  //   width: '150px',
  //   scopedSlots: { customRender: 'action' }
  // }
]
const columnsApp = [
  {
    title: '序号',
    dataIndex: 'serialNumber',
    width: '150px'
    // scopedSlots: { customRender: 'serial' }
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: '200px',
  },
  {
    title: '版本',
    dataIndex: 'version',
    width: '150px'
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    width: '250px',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    CloseSquareOutlined,
    AppModal
  },
  directives: { clickOutside },
  data () {
    this.columns = columns
    this.columnsApp = columnsApp
    return {
      // create model
      visible: false,
      appModalVisible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      selectedRowKeys: [],
      selectedRows: [],

      platformList: [],
      memoryList: [0.5, 1, 1.5, 2, 3, 4, 6, 8],
      form: {
        tagNameId: '',
        internalStorage: '',
        creationTime: [],
        versionNumber: '',

        startTime: '',
        endTime: ''
      },
      appForm: {
        tagName: '',
        tagId: 0
      },
      popoverVisible: false,
      mdlStatus: '',
      pageNum: 0,
      showList: true,
      createTagName: ''
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.getPlatformList()
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    ...mapActions(['pushUploadItemApp']),
      // 加载数据方法 必须为 Promise 对象
    loadData (parameter) {
      const requestParameters = Object.assign({}, parameter, this.queryParam)
      if (this.pageNum) {
        if (this.appForm.tagId) requestParameters.tagId = this.appForm.tagId
        return getAppList(requestParameters).then((res) => {
          return res.data
        })
      } else {
        // if (this.form.tagNameId) requestParameters.tagNameId = this.form.tagNameId
        // if (this.form.internalStorage) requestParameters.internalStorage = `${this.form.internalStorage}`
        // if (this.form.versionNumber) requestParameters.versionNumber = this.form.versionNumber
        // if (this.form.startTime) requestParameters.startTime = moment(this.form.startTime).format('YYYY-MM-DD')
        // if (this.form.endTime) requestParameters.endTime = moment(this.form.endTime).format('YYYY-MM-DD')
        return getTagNameList(requestParameters).then((res) => {
          return res.data
        })
      }
    },
    switchPage () {
      this.pageNum = 0
      this.$refs.table.refresh()
    },
    toApp (e) {
      this.pageNum = 1
      this.appForm.tagName = e.name
      this.appForm.tagId = e.id
      this.$refs.table.refresh()
    },
    formtoList () {
      if (this.form.creationTime.length) {
        this.form.startTime = this.form.creationTime[0]
        this.form.endTime = this.form.creationTime[1]
      }
      this.popoverVisible = false
      this.$refs.table.refresh()
    },
    reformtoList () {
      this.form = {
        tagNameId: '',
        internalStorage: '',
        creationTime: [],
        versionNumber: '',
        startTime: '',
        endTime: ''
      }
      this.popoverVisible = false
      this.$refs.table.refresh()
    },
    async getPlatformList () {
      const param = {
        pageNum: 1,
        pageSize: 5000
      }
      console.log('????')
      const { data } = await getTagNameList(param)
      if (data.data) {
        for (let i = 0; i < data.data.length; i++) {
          this.platformList.push(data.data[i])
        }
      }
    },
    getMemoryList (e) {
      const findData = this.platformList.find((i) => i.id == e)
      this.memoryList = JSON.parse(findData.supports)
      this.form.internalStorage = ''
    },
    // getMemoryOptions(platformId) {
    //   const findData = this.platformOptions.find(i=> i.value == platformId);
    //   return findData?.memoryOptions;
    // },
    getSupportsTest (e) {
      if (!e || !e.length) return '-'
      let text = ''
      const arr = JSON.parse(e)
      for (let i = 0; i < arr.length; i++) {
        text += `${arr[i]}`
        if (i < arr.length - 1) {
          text += '、'
        }
      }
      return text
    },
    handleAdd () {
      // this.mdl = null
      this.mdlStatus = 'add'
      this.appModalVisible = true
    },
    handleEdit (record) {
      this.mdlStatus = 'edit'
      this.mdl = { ...record }
      this.appModalVisible = true
    },
    handleDel (record) {
      const _self = this
      this.confirmLoading = true
      Modal.confirm({
        title: `确定要删除:${record.name}吗？`,
        // icon: createVNode(ExclamationCircleOutlined),
        // content: createVNode('div', { style: 'color:red;' }, 'Some descriptions'),
        onOk () {
          console.log('OK')
          delAppState({ id: record.id }).then((res) => {
            if (res.data.status == 200) {
              _self.$message.success(`删除成功`)
              _self.editVisible = false
              _self.$refs.table.refresh()
            } else {
              _self.$message.error(res.data.msg)
            }
          })
          _self.confirmLoading = false
        },
        onCancel () {
          console.log('Cancel')
          _self.confirmLoading = false
        },
        class: 'test'
      })

      // if (record.status !== 0) {
      //   this.$message.info(`${record.no} 订阅成功`)
      // } else {
      //   this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      // }
    },
    handleEditState (record) {
      const _self = this
      this.confirmLoading = true
      Modal.confirm({
        // title: `确定要${ record.state ? '上线' : '下线' }:${record.name}吗？`,
        title: `此操作将${ record.state ? '下线' : '上线' }状态改为${ record.state ? '上线' : '下线' }状态,是否继续`,
        // icon: createVNode(ExclamationCircleOutlined),
        // content: createVNode('div', { style: 'color:red;' }, 'Some descriptions'),
        onOk () {
          console.log('OK')
          const param = {
            id: record.id,
            state: record.state ? 0 : 1
          }
          setAppState(param).then((res) => {
            if (res.data.status == 200) {
              _self.$message.success(`${ record.state ? '上线' : '下线' }成功`)
              _self.editVisible = false
              _self.$refs.table.refresh()
            } else {
              _self.$message.error(res.data.msg)
            }
          })
          _self.confirmLoading = false
        },
        onCancel () {
          console.log('Cancel')
          _self.confirmLoading = false
        },
        class: 'test'
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const id = values.id
          // console.log("🚀 ~ file: TableList.vue:253 ~ form.validateFields ~ id:", id)
          const api = id > 0 ? updateVersions : addVersion
          new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve()
            }, 1000)
          }).then(async (res) => {
            const { resourcesPath } = values
            const fileUid = resourcesPath?.file?.uid
            const fileName = resourcesPath?.file?.name
            if (fileName) {
              const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
              if (fileType != 'zip' && fileType != 'fup') {
                this.confirmLoading = false
                this.$message.error('仅支持上传zip文件与fup文件!')
                return
              }
            }

            const {
              data: { status: isExistStatus, msg: isExistMsg }
            } = await isExistVersion({
              internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
              tagNameId: values.tagNameId,
              versionNumber: values.versionNumber,
              id
            })
            if (isExistStatus != 200) {
              this.$message.error(isExistMsg)
              this.confirmLoading = false
              return
            }
            // 没有选择上传文件，直接请求新增接口
            if (!fileUid) {
              const {
                data: { status, msg }
              } = await api({
                msg: values.msg,
                internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
                tagNameId: values.tagNameId,
                versionNumber: values.versionNumber,
                resourcesPath: values.resourcesPath,
                id,
                imprint: values.imprint
              })
              if (status != 200) {
                this.$message.error(msg)
                this.confirmLoading = false
                return
              }
            } else {
              const uploadList = this.$store.getters?.getUploadList || {}
              const uploadKey = await computeMD5(resourcesPath?.file)
              this.awaitSubmit({
                key: uploadKey,
                data: {
                  msg: values.msg,
                  tagNameId: values.tagNameId,
                  versionNumber: values.versionNumber,
                  internalStorage: `${values.internalStorage.toString().split('G')[0]}`,
                  md5: uploadKey,
                  resourcesPath: values.resourcesPath,
                  id,
                  imprint: values.imprint
                }
              })
              await sleep(500)
              this.pushUploadItem({
                file: resourcesPath?.file,
                success: () => {
                  // 刷新表格
                  try {
                    this.$refs.table.refresh()
                  } catch (error) {}
                },
                fail: (e) => {
                  console.log('错误')
                  console.log(e)
                }
              })
            }
            this.visible = false
            this.confirmLoading = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success(this.mdlStatus == 'add' ? '新增成功' : '修改成功')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    getPopupContainer () {
      return this.$refs.popoverWrapperRef
    },
    hiddenPopover () {
      this.popoverVisible = false
    },
    async appModalOk (e) {
      e.iconUrl = base64ToFile(e.iconUrl);
      const { tagId } = this.appForm;
      if(!e.id) {
        const md5 = await computeMD5(e.apk.file);
        const icon = await computeMD5(e.iconUrl);
        const { data: { status, msg } } = await verifyAppUpload({
          ...e,
          md5,
          icon,
          url: md5,
          tagId,
        });
        if(status != 200) {
          this.$message.error(msg)
          return;
        }
      }
      this.appModalVisible = false
      this.pushUploadItemApp({
        formData: {
          ...e,
          tagId,
        },
        success: ()=> {
          this.$refs.table.refresh()
          this.$message.success(this.mdlStatus === 'add' ? '上传成功' : '修改成功')
        }
      })
      // const { data: { status, msg } } = await addApp(e)
      // if (status === 200) {
      //   this.$message.success(`上传成功`)
      //   this.appModalVisible = false
      //   this.$refs.appModal.refresh()
      // } else {
      //   this.$message.error(msg)
      // }
    },
    appModalCancel () {
      this.appModalVisible = false
    }
  }
}
</script>
<style>
.div {
  width: 400px;
  margin: 20px;
}
.item {
  margin-bottom: 10px;
}
</style>
